<?php

namespace App\Jobs;

use App\Enums\AssetSourceType;
use App\Enums\AssetStatus;
use App\Enums\TransferSource;
use App\Enums\TransferStatus;
use App\Models\Asset;
use App\Models\TransferRecord;
use App\Services\WalletService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;

class TransferJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /** @var TransferRecord */
    private $record;

    /**
     * Create a new job instance.
     */
    public function __construct(TransferRecord $record)
    {
        $this->record = $record;
    }

    /**
     * Execute the job.
     */
    public function handle(WalletService $walletService)
    {
        $record = $this->record;
        $record->refresh();
        if ($record->status->isNot(TransferStatus::WAITING)) {
            return;
        }
        $asset = $record->asset;
        $transResult = $walletService->transfer(
            $asset->user->mobile,
            $asset->contract_address,
            [$asset->token_id],
            $record->to_user->wallet_address,
        );

        $asset->asset_status = AssetStatus::SOLD();
        $asset->save();

        $record->status = TransferStatus::SUCCESS();
        $record->transfer_time = now();

        //为买方创建资产
        $newAsset = new Asset();
        $newAsset->user_id = $record->to_user_id;
        $newAsset->source_type = AssetSourceType::TRANSFER;
        $newAsset->source_id = $record->id;
        $newAsset->contract_address = $asset->contract_address;
        $newAsset->token_id = $asset->token_id;
        $newAsset->trans_hash = Arr::get($transResult, $asset->token_id);
        $newAsset->asset_status = AssetStatus::HOLD;
        $newAsset->save();

        \DB::transaction(function () use ($record, $asset, $newAsset) {
            $record->save();
            $asset->save();
            $newAsset->save();
        });
        if ($record->source->is(TransferSource::HE_ZHI())) {
            HezhiTradeNotifyJob::dispatch($record);
        }
    }
}
